package io.github.wslxm.springbootplus2.core.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nUtil implements ApplicationContextAware {

    private static MessageSource messageSource;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        messageSource = applicationContext.getBean(MessageSource.class);
    }

    /**
     * 获取当前的 Locale, 如果没有, 自动获取默认 Locale
     */
    public static Locale getCurrentLocale() {
        return LocaleContextHolder.getLocale();
    }

    /**
     * 获取国际化消息
     * @param key 消息的 key
     * @return 国际化消息
     */
    public static String getMessage(String key) {
        // 判断传入值是否为 key
        if (!key.contains(".")) {
            return key;
        }
        Locale currentLocale = getCurrentLocale();
        try {
            String message = messageSource.getMessage(key, null, currentLocale);
            message = message.replaceAll("\"", "");
            return message;
        } catch (NoSuchMessageException e) {
            // String localizedMessage = e.getLocalizedMessage();
            return key;
        }
    }
//
//    /**
//     * 获取带参数的国际化消息
//     * @param key 消息的 key
//     * @param args 消息的参数
//     * @return 国际化消息
//     */
//    public static String getMessage(String key, Object[] args) {
//        return messageSource.getMessage(key, args, getCurrentLocale());
//    }
}
